package ch14;

import javafx.application.Application;
import javafx.beans.binding.StringBinding;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Chooseitems extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    BorderPane mainpane = new BorderPane();
    Selectmode Selectmode1 = new Selectmode();
    Output Output1 = new Output();
    ListView<String> Selectlists = new ListView<String>();

    @Override
    public void start(Stage primaryStage) throws Exception {
        Selectlists.getItems().addAll("1", "2", "3", "4", "5");
        mainpane.setTop(Selectmode1);
        mainpane.setCenter(Selectlists);
        mainpane.setBottom(Output1);
        Scene scene = new Scene(mainpane);
        primaryStage.setScene(scene);
        primaryStage.show();
        StringBinding str = new StringBinding() {
            {
                super.bind(Selectlists.getSelectionModel().selectedItemProperty());
            }

            @Override
            protected String computeValue() {
                String str = "";
                for (String s : Selectlists.getSelectionModel().getSelectedItems()) {
                    str += s + " ";
                }
                return str;
            }
        };
        Output1.output.textProperty().bind(str);
    }

    void setmode() {
        if (Selectmode1.combomode.getValue().equals("单选"))
            Selectlists.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        else
            Selectlists.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    }

    class Selectmode extends HBox {
        Label label1 = new Label("单选还是复选:");
        ComboBox<String> combomode = new ComboBox<>();

        Selectmode() {
            getChildren().clear();
            combomode.getItems().addAll("单选", "复选");
            combomode.setValue("单选");
            combomode.setOnAction(e -> {
                setmode();
            });
            getChildren().addAll(label1, combomode);
        }
    }

    class Output extends HBox {
        Label label1 = new Label("选择了: ");
        Label output = new Label();

        Output() {
            getChildren().clear();
            getChildren().addAll(label1, output);
        }
    }

}